package com.hrbxlh.actionImpl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hrbxlh.dao.ClassDao;
import com.hrbxlh.dao.CourseDao;
import com.hrbxlh.dao.DepartMentDao;
import com.hrbxlh.dao.MemberDao;
import com.hrbxlh.dao.ProfessionDao;
import com.hrbxlh.dao.RelStuClassDao;
import com.hrbxlh.dao.RelationDao;
import com.hrbxlh.dao.SourceDao;
import com.hrbxlh.dao.VirtualMachineManageDao;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.pageUtil;


@Component("classActionImpl")
@Transactional
public class ClassActionImpl {
	
	@Resource(name = "classDao")
	private ClassDao classDao;
	
	@Resource(name = "memberDao")
	private MemberDao memberDao;
	
	@Resource(name = "professionDao")
	private ProfessionDao professionDao;
	
	@Resource(name = "departMentDao")
	private DepartMentDao departMentDao;
	
	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;
	
	@Resource(name = "relationDao")
	private RelationDao relationDao;
	
	@Resource(name = "courseDao")
	private CourseDao courseDao;
	
	@Resource(name="sourceDao")
	private SourceDao sourceDao;
	
	@Resource(name="virtualMachineManageDao")
	private VirtualMachineManageDao virtualMachineManageDao;
	
	@Autowired
    @Qualifier("virtualMachineManageActionImpl")
    private VirtualMachineManageActionImpl virtualMachineManageActionImpl;
	
	/**
	 * @description 添加班级的方法，参数key与数据库column对应即可。 
	 * @param Map<String,Object> paramMap
	 * @return Map<String, String> result true成功，false失败 errorMsg错误信息
	 * @throws Exception
	 */
	public Map<String, Object> addClass(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//添加班级，判断有没有重复的课程
			boolean repeatResult = this.checkRepeat((List<Map<String, Object>>)paramMap.get("relationList"));
			if(repeatResult){ 
				////判断每一个课程与老师之间的关系对不对，有一条不对，就返回失败
				//boolean rightMark= this.checkRightMark((List<Map<String, Object>>)paramMap.get("relationList"));
				//if(rightMark){
				//通过班级名查询班级信息
				List<Map<String, Object>> classList = classDao.getClassByClassName((String)paramMap.get("className"));
				//判断班级名重复
				if(classList !=null && classList.size() != 0){
					resultMap.put("result", false);
					resultMap.put("failMsg", "该班级名已存在");
				}else{
					//添加班级信息，返回班级id
					classDao.addClass(paramMap);
					for(Map<String, Object> map : (List<Map<String, Object>>)paramMap.get("relationList")){
						paramMap.put("stuorteaId", map.get("stuorteaId"));
						paramMap.put("selectMark", 1);
						paramMap.put("courseId", map.get("courseId"));
						//添加表单关联关系  参数paramMap stuorteaId classId  courseId
						classDao.saveClassRelation(paramMap);
						//添加教师与班级的关联信息  注意标识
						relationDao.saveRelClassTeaCourse(paramMap);
						//添加老师与课的关系  注意有没有， 注意标识
						List<Map<String, Object>> relCouTeaList = relationDao.getRelCourseTea(paramMap);
						if(relCouTeaList == null || relCouTeaList.size() == 0){
							relationDao.saveRelCourseTea(paramMap);
						}else{
							//如果之前这个老师和这个课的关联是2，把标识改为3
							if(Integer.parseInt(relCouTeaList.get(0).get("couSelectMark").toString()) == 2){
								//将couSelectMark改为3
								paramMap.put("selectMark", 3);
								relationDao.saveSelectMark(paramMap);
							}
							//修改上课标识inMark为0
							paramMap.put("inMark", 0);
							relationDao.saveInMarkReMark(paramMap);
						}
						paramMap.put("selectMark", 1);
						//添加课与班级的关系  注意标识
						List<Map<String, Object>> relCouClassList = relationDao.getRelCourseClass(paramMap);
						if(relCouClassList == null || relCouClassList.size() == 0){
							relationDao.saveRelCourseClass(paramMap);
						}
					}
					resultMap.put("result", true);
				}	
				//}else{
					//resultMap.put("result", false);
					//resultMap.put("failMsg", "教师关联课程信息错误");
				//}
			}else{
				resultMap.put("result", false);
				resultMap.put("failMsg", "课程选择重复");
			}
		} catch (Exception e) {
			throw e;
		}
		return resultMap;
	}
	
	/**
	 * @description 查询班级的方法
	 * @param Map<String,Object> paramMap,如果有参数，要与数据库column值相同。
	 * @return List<Map<String, Object>> 班级集合
	 * @throws Exception
	 */
	public Map<String, Object> getClass(Map<String, Object> paramMap) throws Exception {

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		Map<String, Object> returnmap = new HashMap<String,Object>();
		try {
			int deaprtMentId = 0;
			resultList = classDao.getClass(paramMap);
			if(resultList!=null&&resultList.size()!=0){
				deaprtMentId = (Integer)resultList.get(0).get("departmentId");
			}
			paramMap.put("departmentId", deaprtMentId);
			//通过院系id查询旗下的所有专业集合
			List<Map<String, Object>> proList = professionDao.getProfessionList(paramMap);
			returnmap.put("resultList", resultList);
			returnmap.put("proList", proList);
		} catch (Exception e) {
			throw e;
		}
		return returnmap;
	}
	
	/**
	 * @description 修改班级的方法，参数key与数据库column一致。 
	 * @param Map<String,Object> paramMap
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public Map<String, Object> saveClass(Map<String,Object> paramMap) throws Exception {

		boolean resultFlag = false;
		String msg = "";
		Map<String,Object> returnMap = new HashMap<String,Object>();
		try {
			//修改班级中的专业院系之后，在学生表里面把院系专业修改掉
			memberDao.saveStuProAndDepartId(paramMap);
			//判断有没有新添加的，如果没有
			if((List<Map<String, Object>>)paramMap.get("addList") == null){
				//修改班级基本信息
				classDao.saveClass(paramMap);
				returnMap.put("result", true);
				//删除要删除的中间表关联信息
				this.delClassRelations(paramMap);
			//有新添加的	
			}else{
				//判断新添加的有没有重复的课程
				boolean repeatResult = this.checkRepeat((List<Map<String, Object>>)paramMap.get("addList"));
				if(repeatResult){ 
					
					//判断每一个课程与老师之间的关系对不对，有一条不对，就返回失败
					//boolean rightMark= this.checkRightMark((List<Map<String, Object>>)paramMap.get("addList"));
					//if(rightMark){
					//判断修改的班级名是否已存在
					Map<String,Object> classMap = classDao.saveGetClassByClassName(paramMap);
					if(classMap==null){
						//删除要删除的中间表关联信息
						this.delClassRelations(paramMap);
						//查询原来就有的这个班级的关联信息append到新加的集合中，然后用哪个方法判断是不是重复，然后才能走下面
						List<Map<String, Object>> addBeforeList = relationDao.getClassRelationByClassId(paramMap);
						addBeforeList.addAll((List<Map<String, Object>>)paramMap.get("addList"));
						boolean repeatResultUse = this.checkRepeat(addBeforeList);
						if(repeatResultUse){
							//修改班级基本信息
							classDao.saveClass(paramMap);
							returnMap.put("result", true);
							
							//添加新添加的关联信息
							if(paramMap.get("addList") != null){
								for(Map<String, Object> map : (List<Map<String, Object>>)paramMap.get("addList")){
									paramMap.put("stuorteaId", map.get("stuorteaId"));
									paramMap.put("selectMark", 1);
									paramMap.put("courseId", map.get("courseId"));
									paramMap.put("classId", paramMap.get("classId"));
									//添加表单关联关系  参数paramMap stuorteaId classId  courseId
									classDao.saveClassRelation(paramMap);
									//0620添加教师与班级的关联信息  注意标识
									List<Map<String, Object>> relClassTeaList = relationDao.getRelClassTea(paramMap);
									if(relClassTeaList == null || relClassTeaList.size() == 0){
										relationDao.saveRelClassTeaCourse(paramMap);
									}
									//0620 end
									//添加老师与课的关系  注意有没有， 注意标识
									List<Map<String, Object>> relCouTeaList = relationDao.getRelCourseTea(paramMap);
									if(relCouTeaList == null || relCouTeaList.size() == 0){
										relationDao.saveRelCourseTea(paramMap);
									}else{
										//如果之前这个老师和这个课的关联是2，把标识改为3
										if(Integer.parseInt(relCouTeaList.get(0).get("couSelectMark").toString()) == 2){
											//将couSelectMark改为3
											paramMap.put("selectMark", 3);
											relationDao.saveSelectMark(paramMap);
										}
										//如果是课程的录入人，需要将inMark改为0
										Map<String, Object> paramUseMap = new HashMap<String, Object>();
										paramUseMap.put("inMark", 0);
										paramUseMap.put("stuorteaId", paramMap.get("stuorteaId"));
										paramUseMap.put("courseId", paramMap.get("courseId"));
										relationDao.saveInMarkReMark(paramUseMap);
									}
									paramMap.put("selectMark", 1);
									//添加课与班级的关系  注意标识
									List<Map<String, Object>> relCouClassList = relationDao.getRelCourseClass(paramMap);
									if(relCouClassList == null || relCouClassList.size() == 0){
										relationDao.saveRelCourseClass(paramMap);
									}else{
										//如果原来存在课程与班级的关系，将结课标识改为0
										paramMap.put("classEndMark", 0);
										courseDao.endCourseClass(paramMap);
									}
									//添加这个班级下的学生与这个课的关联信息
									//查询原来是不是存在这个班级的学生的关联信息（如果有课程和班级的关联关系，就说明已经存在了，如果没有就是没有）
									//查询这个班级下的学生
									List<Map<String, Object>> stuList = relationDao.getStuByClassId(paramMap);
									//0508如果学生是空的不添加
									if(stuList != null && stuList.size() != 0 ){
										Map<String, Object> stuReCourseMap ;
										for(int j = 0;j < stuList.size(); j++){
											stuReCourseMap = new HashMap<String, Object>();
											stuReCourseMap.put("stuorteaId", stuList.get(j).get("stuorteaId"));
											stuReCourseMap.put("courseId", map.get("courseId"));
											stuReCourseMap.put("selectMark", 1);
											//查询这个学生这个课程之前有没有关联信息，如果没有就添加
											Map<String, Object> reListMap = relStuClassDao.getRelStuCouByStuCou(stuReCourseMap);
											if(reListMap == null){
												relationDao.saveRelCourseTea(stuReCourseMap);
											}else{
												//如果存在这个学生与这个课的关联，把结课标识改为0
												stuReCourseMap.put("endMark", 0);
												classDao.saveRelStuCouEndMark(stuReCourseMap);
											}		
										}
									}
								}
							}
						}else{
							returnMap.put("result", false);
							returnMap.put("failMsg", "课程选择重复");
						}
						
					}else{
						returnMap.put("result", false);
						returnMap.put("failMsg", "班级名重复，修改失败");
					}
					//}else{
						//returnMap.put("result", false);
						//returnMap.put("failMsg", "教师关联课程信息错误");
					//}
				}else{
					returnMap.put("result", false);
					returnMap.put("failMsg", "课程选择重复");
				}
			}
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/**
	 * @description 删除班级的方法，传的是每个班级的id。 
	 * @param .List<Integer> paramList 班级id集合
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 * 备注：删除班级的时候直接把旗下的学生直接删除
	 */
	public boolean delClass(List<String> paramList,int marks) throws Exception {

		boolean resultFlag = false;
		try {
			//解除某班级下所有学生的虚拟机绑定
			Map<String, Object> vmParam = new HashMap<String, Object>();
			vmParam.put("classId", paramList.get(0));
			//通过班级id查人员id的集合
			List<String> idList = memberDao.getUseIdList(paramList);
			if(marks==1){
				//调用删除所有相关的方法
				resultFlag = this.delMethod(paramList,marks,vmParam,idList,paramList.get(0));
			}if(marks==2){
				try{
					virtualMachineManageActionImpl.deleteVirtualMachineClass(vmParam);
					
				}catch(Exception e){
					e.printStackTrace();
				}
				resultFlag = this.delMethod(paramList,marks,vmParam,idList,paramList.get(0));
			}
		} catch (Exception e) {
			throw e;
		}
		return resultFlag;
	}
	
	//删除班级所有相关的方法
	public boolean delMethod(List<String> paramList,int marks,Map<String, Object> vmParam,List<String> idList,Object classId){
		boolean flag = false;
	   try{
		   virtualMachineManageDao.unallocateVirtualMachineByClass(vmParam);
			//删除班级虚拟机集群配置信息
			virtualMachineManageDao.deleteVirtualMachineClass(vmParam);
			//删除班级学生关联表
			flag =	relStuClassDao.delRelStuClassByClassId(paramList);
			//删除课程班级关联表
			flag = relStuClassDao.delRelcourseClassByClassId(paramList);
			//通过班级号删除消息班级关联表
			flag = relStuClassDao.delRelnotClassByClassId(paramList);
			//通过班级号删除教师班级关联表
			flag =	relStuClassDao.delRelteaClassByClassId(paramList);
			//删除人与课程的关联表
			if(idList!=null&&idList.size()!=0){
				flag =relStuClassDao.delRelstuCouByStuorteaIdClass(idList);
				//删除学生成绩表
				flag =	sourceDao.delStuSoruceBystuorteaId(idList);
			}
			//0927begin通过classId将这个班级的所有课程，老师的关联取出来
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("classId", classId);
			List<Map<String, Object>> teacouList = classDao.getClassRelation(paramMap);
			//删除这些教师与这些课程的关联，（注意判断是不是录入教师，如果是，修改标识即可，不删除，如果不是录入教师，删除关联课程的信息）
			this.delTeaAndCouRelation(teacouList);
			//0927end
			//批量删除classrelation表中的数据,参数是班级id
			classDao.delClassRelations(paramList);
			//删除班级下的人
			flag = memberDao.delMemberByClassId(paramList);
			//删除班级
			flag = classDao.delClass(paramList);
	   }catch(Exception e){
		   e.printStackTrace();
	   }
		return flag;
	}

	
	/**
	 * @description 删除这些教师与这些课程的关联，（注意判断是不是录入教师，如果是，修改标识即可，不删除，如果不是录入教师，删除关联课程的信息）
	 * @param 
	 * @return 
	 * @throws Exception
	 */
	public boolean delTeaAndCouRelation(List<Map<String, Object>> paramList) throws Exception{
		boolean result = false;
		try{
			Map<String, Object> courseMap = new HashMap<String, Object>();
			//查询每一个教师与课程的关系，如果是录入教师 修改关联信息，如果不是录入教师，将教师课程关联删除
			for(Map<String, Object> map : paramList){
				//查询这个课程全部信息
				courseMap = courseDao.getCourseDetail(map);
				//如果是录入人，修改标识，
				if(map.get("stuorteaId").toString().equals(courseMap.get("stuorteaId").toString())){
					map.put("inMark", 1);
					relationDao.saveInMarkReMark(map);
				//不是录入人信息，将关联删除
				}else{
					relationDao.delCourseReTeacher(map);
				}
			}
			result = true;
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
	
	/**
	 * @description 查询班级列表的方法，分页。
	 * @param Map<String,Object> paramMap 当前页数：pageNow，每页条数：pageSize，其他条件与column列值要一致。
	 * @return Map<String, Object> memberList：班级集合，pageNow：当前页数，totalPage：总页数
	 * @throws Exception
	 */
	public Map<String, Object> getClassList(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		try {
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//查询所有班级
			List<Map<String, Object>> classList = classDao.getClass(paramMap);
			
			//将班级人数和班级合到一起放到新的集合里 
			for(int i=0;i<classList.size();i++){
				Map<String, Object> newMap = new HashMap<String, Object>();
				//查询每个班级拥有的人数
				List<Map<String, Object>> coutList = memberDao.getStuCountByClassId(String.valueOf(classList.get(i).get("classId")));
				newMap.put("classId", classList.get(i).get("classId"));
				newMap.put("className", classList.get(i).get("className"));
				newMap.put("stuCount", coutList.get(0).get("stuCount"));
				newMap.put("departmentName", classList.get(i).get("departmentName"));
				newMap.put("professionName", classList.get(i).get("professionName"));
				resultList.add(newMap);
			}
			returnMap.put("classList", resultList);
			returnMap.put("pageNow", pageNow);
			
			//获取全部页数,全部班级名（搜素框用到的）
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = classDao.getClass(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);
			returnMap.put("selectclaList", allMemberList);
			//获取所有院系信息
			paramMap.put("departmentName", "");
			paramMap.put("departmentId", "");
			List<Map<String, Object>> departMentList = departMentDao.getDepartMentList(paramMap);
			returnMap.put("departMentList", departMentList);
			
			//获取所有专业信息
//			List<Map<String, Object>> professionList = professionDao.getProfessionList(paramMap);
//			returnMap.put("professionList", professionList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}
	
	/*
	 * 导入
	 */
	 public  Map<String,Object> imStuExcelByClass(String file,int classId,String type) throws Exception{
		//得到表格中所有的数据
       List<Map<String, Object>> listExcel= new ArrayList<Map<String, Object>>();
       //处理后数据的集合
       List<Map<String, Object>> finalList= new ArrayList<Map<String, Object>>();
      //查询每个班级对应的课程集合
       List<Map<String, Object>> courseList= new ArrayList<Map<String, Object>>();
       //参数map
       Map<String, Object> paramMap = new HashMap<String,Object>();
       
     //课程和学号map
       Map<String, Object> excelMap = new HashMap<String,Object>();
       paramMap.put("classId", classId);
       //返回结果的Map
       Map<String, Object> returnMap = new HashMap<String,Object>();
       boolean findFlag = false;
       boolean addFlag = false;
       boolean courseFlag = false;
       if(type.equals("1")){
    	   //查询每个班级对应的课程
    	   courseList =relStuClassDao.getRelCourseByClassId(paramMap);
    	   System.out.println("没有课程吗"+courseList+"aa"+courseList.size());
    	   excelMap = this.getAllStudentByExcel(file,classId);
    	   listExcel = (List<Map<String, Object>>) excelMap.get("list");
    	   if(listExcel!=null&&listExcel.size()!=0){
    		   //查询当前班级所属的院系和专业
    		  Map<String,Object> classMap = classDao.getDeAndProByClassId(paramMap);
    		   if(courseList.size()!=0&&courseList!=null){
        		   for(int i=0;i<courseList.size();i++){
            		   for(int j=0;j<listExcel.size();j++){
            			   //课程和学号map
            		       Map<String, Object> couStuMap = new HashMap<String,Object>();
                		   couStuMap.put("stuorteaId", listExcel.get(j).get("stuorteaId"));
                		   couStuMap.put("courseId", courseList.get(i).get("courseId"));
                		   //将该班级所属院系加入学生中
                		   listExcel.get(j).put("professionId", classMap.get("professionId"));
                		   listExcel.get(j).put("departmentId", classMap.get("departmentId"));
                		   System.out.println("传给的课程对象不对吗"+couStuMap);
                		   //查询当前人是否和当前课程有
                		   Map<String,Object> relMap = relStuClassDao.getRelStuCouByStuCou(couStuMap);
                		   System.out.println("得到的课程"+relMap);
                		   if(relMap==null){
                			   finalList.add(couStuMap); 
                		   }
                	   }
            	   }
        		   if(finalList!=null&&finalList.size()!=0){
        			   findFlag = true;
        		   }
        	   }else{
        		   for(int j=0;j<listExcel.size();j++){
            		   //将该班级所属院系加入学生中
            		   listExcel.get(j).put("professionId", classMap.get("professionId"));
            		   listExcel.get(j).put("departmentId", classMap.get("departmentId"));
            	   }
        		   addFlag = true;
        		   courseFlag = true;
        	   }
    	   }else{
    		   findFlag = false;
    		   addFlag = false;
    	   }
    	   System.out.println("如果是导入教师就不应该走这"+type+"最后的集合"+finalList);
    	   System.out.println("正确与否"+type.equals("1"));
    	   if(findFlag){
        	   //将课程id和学生Id存入relstucou表中
        	   courseFlag  = relStuClassDao.addRelstuCouByStuAndCou(finalList);
        	   System.out.println("添加测试关联"+courseFlag);
           }
    	   
       }if(type.equals("2")){
    	   excelMap = this.getAllByExcel(file);
    	   System.out.println(excelMap);
    	   listExcel = (List<Map<String, Object>>) excelMap.get("list");
    	   System.out.println("添加教师"+listExcel);
    	   addFlag = true;
    	   courseFlag = true;
       }
      
       if(!courseFlag&&finalList.size()!=0){
    	   System.out.println("添加课程出错");
    	   returnMap.put("msg","fail");
    	   returnMap.put("errMsg","添加课程出错");
       }if(!courseFlag&&finalList.size()==0&&addFlag){
    	   System.out.println("当前信息已被导入，请重新操作");
    	   returnMap.put("msg","fail");
    	   returnMap.put("errMsg","当前信息已被导入，请重新操作");
       }else{
    	   addFlag = true;
       }
       Map<String,Object>  sourceMap = new HashMap<String,Object>();
       sourceMap.put("classPerformance", 0.4);
	   sourceMap.put("excellent", 4);
	   sourceMap.put("good", 3);
	   sourceMap.put("inso", 2);
	   sourceMap.put("bad", 1);
       if(addFlag){
    	  
           String pwd = "";
    	   String password = "";
           if(listExcel!=null&&listExcel.size()!=0){
        	   System.out.println("得到表格中所有的数据"+classId+"表格的长度"+listExcel.size());
        	   for (int i=0;i<listExcel.size();i++) {
                   String stuorteaId =String.valueOf(listExcel.get(i).get("stuorteaId"));
                   //查询这条记录是否已存在
                   List<Map<String, Object>> memberList = memberDao.getMemberByStuorteaId(stuorteaId);
                   if (memberList==null||memberList.size()==0) {
                	   System.out.println("添加");
                	   listExcel.get(i).put("classId", classId);
                	   pwd = stuorteaId+"000000";
                	   password = DigestUtils.md5Hex(pwd);
                	   listExcel.get(i).put("password",password);
           				//不存在就添加(数据库)
                	   boolean addflag = memberDao.addMember(listExcel.get(i));
                	   if(addflag&&type.equals("1")){
                		 //向relstuclass表插入数据
                    	   Map<String, Object> paraMap = new HashMap<String,Object>();
                    	   paraMap.put("classId", classId);
                    	   paraMap.put("stuorteaId", stuorteaId);
                    	   boolean flag = relStuClassDao.addRelStuClass(paraMap);
                    	   if(!flag){
                    		   returnMap.put("msg", "fail");
                    		   returnMap.put("errMsg",excelMap.get("errMsg"));
                    	   }else{
                    		   returnMap.put("msg", "success");
                    	   }
                	   }if(addflag&&!(type.equals("1"))){
                		   //添加的是教师----将添加的教师对应的成绩设置设置为默认
                		   sourceMap.put("stuorteaId", stuorteaId);
                		  boolean flag = sourceDao.addSorceSet(sourceMap);
                		  if(flag){
                			  returnMap.put("msg", "success");
                		  }else{
                			  returnMap.put("msg", "fail");
                   		   	  returnMap.put("errMsg","成绩设置失败，添加教师失败");
                		  }
                		 
                	   }if(!addflag){
                		   returnMap.put("msg", "fail");
                		   returnMap.put("errMsg",excelMap.get("errMsg"));
                	   }
                	  
                   }else {
                	   System.out.println("修改");
                	   listExcel.get(i).put("classId", classId);
                	   pwd = stuorteaId+"000000";
                	   password = DigestUtils.md5Hex(pwd);
                	   listExcel.get(i).put("password",password);
                       //存在就更新
                	  boolean saveflag = memberDao.saveMember(listExcel.get(i));
                	  if(!saveflag){
               		   returnMap.put("msg", "fail");
               		   returnMap.put("errMsg",excelMap.get("errMsg"));
               	   }else{
               		   returnMap.put("msg", "success");
               	   }
                   }
               }
           }if(String.valueOf(excelMap.get("flag")).equals("success")){
        	   //说明当前用户要导入学生所属班级不存在
        	   returnMap.put("msg","success");
           }if(listExcel==null||listExcel.size()==0&&!(String.valueOf(excelMap.get("flag")).equals("success"))){
        	   returnMap.put("msg","fail");
        	   returnMap.put("errMsg",excelMap.get("errMsg"));
        	   
           }
       }else{
    	   returnMap.put("msg","fail");
    	   if(returnMap.get("errMsg")!=""&&returnMap.get("errMsg")!=null){
    		   
    	   }else{
    		   returnMap.put("errMsg",excelMap.get("errMsg"));
    	   }
    	   
       }
       
       return returnMap;
   }
	 
	 /**
	    * 查询指定目录中电子表格中所有的数据
	    * @param file 文件完整路径
	    * @return
	    */
   public  Map<String, Object> getAllByExcel(String file){
       List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
       Map<String, Object> returnMap = new HashMap<String,Object>();
       try {
           Workbook rwb=Workbook.getWorkbook(new File(file));
           Sheet rs=rwb.getSheet(0);
           int clos=rs.getColumns();//得到所有的列
           int rows=rs.getRows();//得到所有的行
           
           System.out.println(clos+" rows:"+rows);
           int newRow = PubMethods.getTeaMemNewRows(rows, rs);
           ok:
           for (int i = 2; i <= newRow; i++) {
               for (int j = 0; j < clos; j++) {
            	   Map<String, Object> resultMap = new HashMap<String,Object>();
                   //第一个是列数，第二个是行数
                   String userName=rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
                   if(userName.equals("")||userName.equals(null)){
                	   System.out.println(1);
                	   returnMap.put("flag", "fail");
                	   returnMap.put("errMsg", "姓名不能为空，导入教师失败");
                	   returnMap.put("list", null);
                	   break ok;
                   }else{
                	   System.out.println(2);
                       String stuorteaId=rs.getCell(j++, i).getContents().trim();
                	   if(stuorteaId.equals("")||stuorteaId.equals(null)){
                		   System.out.println(3);
                    	   returnMap.put("flag", "fail");
                    	   returnMap.put("errMsg", "工号不能为空，导入教师失败");
                    	   returnMap.put("list", null);
                    	   break ok;
                       }else{
                    	   if(stuorteaId.length()<4||stuorteaId.length()>20){
                        	   System.out.println(71);
                        	   returnMap.put("flag", "fail");
                        	   returnMap.put("errMsg", "工号请输入4~20位数字或英文，导入教师失败");
                        	   returnMap.put("list", null);
                        	   break ok;
                           }else{
                        	   System.out.println(4);
                        	   boolean idFlag = PubMethods.isStrChinese(stuorteaId);
                        	   if(!idFlag){
                        		   System.out.println(21);
                        		   String userSex=rs.getCell(j++, i).getContents().trim();
                            	   if(userSex.equals("")||userSex.equals(null)){
                            		   System.out.println(5);
                            		   returnMap.put("flag", "fail");
                                	   returnMap.put("errMsg", "性别不能为空，导入教师失败");
                                	   returnMap.put("list", null);
                                	   break ok;
                            	   }else{
                            		   System.out.println(6);
                            		   String sex = "m";
                                       if(userSex.equals("女")){
                                       	sex="f";
                                       }
                                       
                                	   String departmentName=rs.getCell(j++, i).getContents().trim();
                                	   if(departmentName.equals("")||departmentName.equals(null)){
                                		   System.out.println(9);
                                		   returnMap.put("flag", "fail");
                                    	   returnMap.put("errMsg", "院系不能为空，导入教师失败");
                                    	   returnMap.put("list", null);
                                    	   break ok;
                                	   }else{
                                		   System.out.println(10);
                                		   String professionName=rs.getCell(j++, i).getContents().trim();
                                		   if(professionName.equals("")||professionName.equals(null)){
                                			   System.out.println(11);
                                    		   returnMap.put("flag", "fail");
                                        	   returnMap.put("errMsg", "专业不能为空，导入教师失败");
                                        	   returnMap.put("list", null);
                                        	   break ok;
                                    	   }else{
                                    		   System.out.println(12);
                                    		 //通过专业名查询专业id
                                               List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
                                               Map<String, Object> paramMap = new HashMap<String,Object>();
                                               paramMap.put("professionName", professionName);
                                               returnList=professionDao.getProfessionList(paramMap);
                                             //通过院系名查询院系id
                                               List<Map<String, Object>> departList = new ArrayList<Map<String, Object>>();
                                               paramMap.put("departmentName", departmentName);
                                               departList=departMentDao.getDepartMentList(paramMap);
                                               int departmentId = 0;
                                               int professionId = 0;
                                               int prodepartmentId = 0;
                                               if(departList!=null&&departList.size()!=0){
                                            	   departmentId = Integer.parseInt(String.valueOf(departList.get(0).get("departmentId")));   
                                            	   System.out.println("当前院系id是"+departmentId);
                                            	   if(returnList!=null&&returnList.size()!=0){
                                                	   professionId = Integer.parseInt(String.valueOf(returnList.get(0).get("professionId")));
                                                	   prodepartmentId = Integer.parseInt(String.valueOf(returnList.get(0).get("departmentId")));
                                                	   System.out.println("当前专业对应的院系id是"+departmentId);
                                                	   //查询当前专业所属院系是否和填写的院系相符
                                                	   if(departmentId==prodepartmentId){
                                                		   if(returnList!=null&&returnList.size()!=0&&departList!=null&&departList.size()!=0){
                                                        	   System.out.println(13);
                                                        	   String telephoneNum=rs.getCell(j++, i).getContents().trim();
                                                        	   boolean telFlag = PubMethods.isMobileNum(telephoneNum);
                                                        	   if(telFlag){
                                                        		   System.out.println(14);
                                                        		   System.out.println("userName"+userName+" stuorteaId:"+stuorteaId+" sex:"+sex+" professionId:"+professionId+"departmentId"+departmentId+"telephoneNum"+telephoneNum);
                                        	                       resultMap.put("userName", userName);
                                        	                       resultMap.put("stuorteaId", stuorteaId);
                                        	                       resultMap.put("userSex", sex);
                                        	                       resultMap.put("professionId", professionId);
                                        	                       resultMap.put("departmentId", departmentId);
                                        	                       resultMap.put("telephoneNum", telephoneNum);
                                        	                       resultMap.put("password", "");
                                        	                       resultMap.put("roleId",2);
                                        	                       resultMap.put("depId", 0);
                                        	                       resultMap.put("staff_role", 1);
                                        	                       resultMap.put("headIcon", "");
                                        	                       resultMap.put("userContect", "");
                                        	                       resultMap.put("imageUrl", "teamr.jpg");
                                        	                       resultMap.put("mem_type", 2);//标识添加的是教师
                                        	                       list.add(resultMap);
                                        	                       returnMap.put("list", list);
                                                        	   }else{
                                                        		   System.out.println(15);
                                                        		   returnMap.put("flag", "fail");
                                                            	   returnMap.put("errMsg", "手机号输入不正确，导入教师失败");
                                                        		   list = null;  
                                                        		   returnMap.put("list", list);
                                                            	   break ok;
                                                        	   }
                                                        	   
                                                           }
                                                	   }else{
                                                		   System.out.println(17);
                                                    	   list = null; 
                                                    	   returnMap.put("flag", "fail");
                                                    	   returnMap.put("errMsg", "填写院系中没有相应的专业，导入教师失败");
                                                    	   returnMap.put("list", list);
                                                    	   break ok;
                                                	   }
                                                   }else{
                                                	   System.out.println(18);
                                                	   returnMap.put("flag", "fail");
                                                	   returnMap.put("errMsg", "没有此专业，导入教师失败");
                                                	   list = null;  
                                                	   returnMap.put("list", list);
                                                	   break ok;
                                                   }
                                               }else{
                                            	   System.out.println(16);
                                            	   returnMap.put("flag", "fail");
                                            	   returnMap.put("errMsg", "没有此院系，导入教师失败");
                                            	   list = null;  
                                            	   returnMap.put("list", list);
                                            	   break ok;
                                               }
                                    	   }
                                           
                                	   }
                            	   }
                        	   }else{
                        		   System.out.println(20);
                            	   returnMap.put("flag", "fail");
                            	   returnMap.put("errMsg", "工号不能为中文，导入教师失败");
                            	   list = null;  
                            	   returnMap.put("list", list);
                            	   break ok;
                        	   }
                           }
                       }
                   }
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       } 
       return returnMap;
       
   }
   
   /**
    * 查询指定目录中电子表格中所有的数据
    * @param file 文件完整路径
    * @return
    */
   public  Map<String, Object> getAllStudentByExcel(String file,int classId){
	   List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
	   Map<String, Object> returnMap = new HashMap<String,Object>();
	   try {
	       Workbook rwb=Workbook.getWorkbook(new File(file));
       Sheet rs=rwb.getSheet(0);
       
       int clos=rs.getColumns();//得到所有的列
       int rows=rs.getRows();//得到所有的行
       
       System.out.println(clos+" rows:"+rows);
       int newRow = PubMethods.getMemNewRows(rows, rs);
       int count=0;
       ok:
       for (int i = 5; i < newRow+5; i++) {
    	   count++;
    	   System.out.println("count="+count);
    	   if(count<newRow){
    		   oh:
    		   for (int j = 1; j < 6; j++) {
            	   System.out.println("i"+i);
            	   Map<String, Object> resultMap = new HashMap<String,Object>();
                   //第一个是列数，第二个是行数
                   String stuorteaId=rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
                   System.out.println("stuorteaId"+stuorteaId);
                   if(stuorteaId.equals("")||stuorteaId.equals(null)){
                	   System.out.println(1);
                	   returnMap.put("flag", "fail");
                	   returnMap.put("errMsg", "学号不能为空，导入学生失败");
                	   returnMap.put("list", null);
                	   break ok;
                   }else{
                	   System.out.println(2);
                	   if(stuorteaId.length()!=10){
                    	   System.out.println(71);
                    	   returnMap.put("flag", "fail");
                    	   returnMap.put("errMsg", "学号请输入10位数字或英文，导入学生失败");
                    	   returnMap.put("list", null);
                    	   break ok;
                       }else{
                    	   boolean idFlag = PubMethods.isStrChinese(stuorteaId);
                    	   if(!idFlag){
                    		   System.out.println(21);
                    		   String userName=rs.getCell(j++, i).getContents().trim();
                               if(userName.equals("")||userName.equals(null)){
                            	   System.out.println(3);
                            	   returnMap.put("flag", "fail");
                            	   returnMap.put("errMsg", "姓名不能为空，导入学生失败");
                            	   returnMap.put("list", null);
                            	   break ok;
                               }else{
                            	   System.out.println(4);
                            	   String userSex=rs.getCell(j++, i).getContents().trim();
                            	   if(userSex.equals("")||userSex.equals(null)){
                            		   System.out.println(5);
                            		   returnMap.put("flag", "fail");
                                	   returnMap.put("errMsg", "性别不能为空，导入学生失败");
                                	   returnMap.put("list", null);
                                	   break ok;
                            	   }else{
                            		   System.out.println(18);
                            		   String sex = "m";
                                       if(userSex.equals("女")){
                                       	sex="f";
                                       }
                                	   String className=rs.getCell(j++, i).getContents().trim();
                                	   System.out.println(className);
                                	   //通过班级名查询当前输入的班级是否和要导入班级相匹配
                                	   List<Map<String,Object>> classList = classDao.getClassByClassName(className);
                                	   boolean telFlag = false;
                                	   if(classList!=null&&classList.size()!=0){
                                		   if(Integer.valueOf(String.valueOf(classList.get(0).get("classId")))==classId){
                                			   telFlag = true;
                                		   }
                                    	   System.out.println(telFlag);
                                    	   if(telFlag){
                                    		   System.out.println("userName"+userName+" stuorteaId:"+stuorteaId+" sex:"+sex);
                                               resultMap.put("userName", userName);
                                               resultMap.put("stuorteaId", stuorteaId);
                                               resultMap.put("userSex", sex);
                                               resultMap.put("professionId", 0);
                                               resultMap.put("departmentId", 0);
                                               resultMap.put("telephoneNum", "");
                                               resultMap.put("password", "");
                                               resultMap.put("roleId",1);
                                               resultMap.put("depId", 0);
//                                               resultMap.put("age", finage);
                                               resultMap.put("headIcon", "");
                                               resultMap.put("userContect", "");
                                               resultMap.put("imageUrl", "");
                                               list.add(resultMap);
                                               returnMap.put("list", list);
                                    	   }else{
                                    		   System.out.println("要导入的班级不是你输入的班级");
                                           } 
                                	   }else{
                                		 System.out.println("没有此班级");
                                		 returnMap.put("flag", "success");
                                		  break oh;
                                	   }
                                	   
                            	   }
                            	   
                               }
                    		   
                    	   }else{
                    		   System.out.println(20);
                    		   returnMap.put("flag", "fail");
                        	   returnMap.put("errMsg", "学号不能为中文，导入学生失败");
                        	   list = null;  
                        	   returnMap.put("list", list);
                        	   break ok;
                    	   }
                       }
                   }
               }
    	   }else{
    		   break ok;
    	   }
       }
       System.out.println("方法最后返回的map是0"+returnMap);
   } catch (Exception e) {
       // 
       e.printStackTrace();
   } 
   return returnMap;
   
}
   
   
   /**date：2017-04-07 xzx
	 * @description 查询某班级详细信息
	 * @param classId
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getClassMsgById(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> map = new HashMap<String , Object>();
		try{
			map = classDao.getClassMsgById(paramMap);
		}catch(Exception e){
			throw e;
		}
		return map;
	}
	
	 /**date：2017-06-13 xzx
	 * @description 查询某班级详细信息 只有班级名字  
	 * @param classId
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getClassNameById(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> map = new HashMap<String , Object>();
		try{
			map = classDao.getClassNameById(paramMap);
		}catch(Exception e){
			throw e;
		}
		return map;
	}
   
	/**xzx
	 * @param request
	 * @param response
	 * @return  判断一个数组里是否有重复值
	 * @throws Exception 
	 * @throws IOException
	 */
	public boolean checkRepeat(List<Map<String, Object>> paramList) throws Exception{
	  
	    Set<Integer> set = new HashSet<Integer>();
		boolean result = false;
	    try{
		    for(Map<String, Object> map : paramList){
			    int courseId = (Integer)map.get("courseId");
			    set.add(courseId);
		    }
		    //有重复
		    if(set.size() != paramList.size()){
		    	result =  false;
		    //不重复
		    }else{
		    	result = true;
		    }
		}catch(Exception e){
			throw e;
		}
	    return result;
	}
	
	/**xzx
	 * @param request
	 * @param response
	 * @return  查询得到的课程老师之间关系是否正确，如有一条不正确返回失败
	 * @throws Exception 
	 * @throws IOException
	 */
	public boolean checkRightMark(List<Map<String, Object>> paramList) throws Exception{
	  
		boolean result = false;
		int rightLength = 0;
	    try{
	    	for(Map<String, Object> map : paramList){
	    		map.put("couSelectMark", 1);//注意找等于1或3的
	    		Map<String, Object> teacherMap = relationDao.getTeacherByCourseIdAndMark(map);
	    		//没有关联关系的课程可以
	    		if(teacherMap == null){
	    			rightLength += 1;
	    		}else{
	    			//课程有上课老师，并且上课老师还是这个老师，可以
	    			if(((String)teacherMap.get("stuorteaId")).equals((String)map.get("stuorteaId"))){
	    				rightLength += 1;
	    			}
	    		}
	    	}
	    	if(rightLength == paramList.size()){
	    		result = true;
	    	}
	    	
		}catch(Exception e){
			throw e;
		}
	    return result;
	}
	
	 /**date：2017-06-08 xzx
	 * @description 修改班级的位置，返回关联信息，下面带加号的 ,参数是班级id
	 * @param classId
	 * @return Map
	 * @throws Exception
	 */
	public List<Map<String, Object>> getClassRelation(Map<String, Object> paramMap) throws Exception{
		
		List<Map<String, Object>> list = new ArrayList<Map<String , Object>>();
		try{
			list = classDao.getClassRelation(paramMap);
		}catch(Exception e){
			throw e;
		}
		return list;
	}
	
	 /**date：2017-06-08 xzx
	 * @description 修改班级的时候删除一条关联信息的删除方法 并且恢复关联数据
	 * @param classId stuorteaId courseId
	 * @return Map
	 * @throws Exception
	 */
	public boolean delClassRelations(Map<String, Object> paramMap) throws Exception{
		
		boolean result = false;
		try{
			if(paramMap.get("delList") != null){
				List<Map<String, Object>> delList = (List<Map<String, Object>>)paramMap.get("delList");
				for(Map<String, Object> map : delList){
					//删除classrelation表里面的数据,参数是班级id，课程id，老师id
					classDao.delClassRelation(map);
					//删除教师与班级的关系
					relationDao.delClassReTeacherNew(map);
					//删除课与班级的关系,参数为课程id，班级Id
					relationDao.delCourseRelClass(map);
					//恢复关联信息开始
					//查询这个课程的录入人id
					Map<String, Object> courseDetail = courseDao.getCourseDetail(map);
					//查询这个课这个老师之间的关系
					List<Map<String, Object>> relationList = relationDao.getRelCourseTea(map);
					//如果是录入老师，将录入标识改为1
					if(((String)courseDetail.get("stuorteaId")).equals((String)map.get("stuorteaId"))){
						map.put("inMark", 1);
						relationDao.saveInMarkReMark(map);
					//不是录入老师	
					}else{
						if(relationList != null){
							if(relationList.size() != 0){
								//如果原来的关系是3，将关系改为2，并且不删除关系
								if(Integer.parseInt(relationList.get(0).get("couSelectMark").toString()) == 3){
									map.put("selectMark", 2);
									relationDao.saveSelectMark(map);
								}else{
									//删除教师与课程之间的关系
									relationDao.delCourseReTeacher(map);
								}
							}
						}
					}
					//删除这个班级下学生与这个课程的关联关系
					relationDao.delMyStuCourseRel(map);
					//删除课表中属于这个课的课表信息，标识是1
					map.put("couSelectMark", 1);
					relationDao.delRelation(map);
				}
				result = true;
			}
		}catch(Exception e){
			throw e;
		}
		return result;
	}
	
	 /**date：2017-06-08 xzx
	 * @description 获取该班级对应的课程以及任课教师信息
	 * @param classId
	 * @return Map
	 * @throws Exception
	 */
	public List<Map<String, Object>> getCourseByClassId(Map<String, Object> paramMap) throws Exception{
		
		List<Map<String, Object>> list = new ArrayList<Map<String , Object>>();
		try{
			list = classDao.getCourseByClassId(paramMap);
		}catch(Exception e){
			throw e;
		}
		return list;
	}
	
	 /**date：2017-06-09 xzx
	 * @description 获取某个课程的教师排课类型的上课教师
	 * @param courseId
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getTeacherByCourseIdAndMark(Map<String, Object> paramMap) throws Exception{
		
		Map<String, Object> map = new HashMap<String, Object>();
		try{
			map = relationDao.getTeacherByCourseIdAndMark(paramMap);
		}catch(Exception e){
			throw e;
		}
		return map;
	}

}
